<template>
  <div :class="projectType ? 'login-wrap1' : 'login-wrap'">
    <div class="ms-login">
      <div class="ms-title">{{ project_Name }}</div>
      <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
        <el-form-item prop="username">
          <el-input v-model="param.userName" placeholder="请输入用户名">
            <template #prepend>
              <el-button icon="el-icon-user"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="请输入密码" show-password v-model="param.passWord"
            @keyup.enter="submitForm()">
            <template #prepend>
              <el-button icon="el-icon-lock"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <div class="find_password" @click="handleEdit(1, {})">找回密码</div>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm()">登录</el-button>
        </div>
        <p class="login-tips">Tips : 用户名和密码。</p>
      </el-form>
    </div>
    <el-dialog title="找回密码" v-model="editVisible" :close-on-click-modal="false" width="40%">
      <el-form label-width="70px">
        <el-form-item label="手机号">
          <el-input v-model="form.moblie"></el-input>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="15">
              <el-input class="inputwidth" v-model="form.smsCode"></el-input></el-col>
            <el-col :span="3">
              <el-button v-show="showtime" @click="sendCode()">
                <span v-if="count == 0">重新发送</span>
                <span v-else>{{ count }}</span>
              </el-button>
              <el-button v-show="!showtime" @click="sendCode()">
                <span>重新发送（{{ count }}s）</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="form.password" show-password></el-input>
          <div class="passw">
            密码长度8-20个字符，可包含字母（区分大小写）,数字（除空格）元素
          </div>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="form.affirm_password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, computed } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import { PermissionsPage } from "../assets/js/permission";
import operate from "../assets/js/operatePermission";
import { DateMinus } from "../assets/js/getcampusList";
import pars from "../assets/js/parsing";
import api from "../api/api";
export default {
  setup() {
    const router = useRouter();
    let { proxy } = getCurrentInstance();
    const param = reactive({
      userName: "",
      passWord: "",
    });
    const projectType = ref(false);
    const project_Name = ref("");
    const location_host = window.location.host;
    if (location_host.indexOf("dalimanage") != -1) {
      projectType.value = true;
      project_Name.value = "智慧用电安全隐患监管服务平台";
    } else {
      projectType.value = false;
      project_Name.value = "数字物联综合管理平台";
    }
    const rules = {
      userName: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };
    const login = ref(null);
    const loading = ref(null);
    // const store1 = useStore();
    // const collapse = computed(() => (store1.state.collapse = false));
    const submitForm = () => {
      if (param.userName == "") {
        ElMessage.error("请输入用户名");
        return;
      } else if (param.passWord == "") {
        ElMessage.error("请输入密码");
        return;
      } else {
        // store1.commit("handleCollapse", !collapse.value);
        localStorage.setItem("projectName", "");
        localStorage.setItem("projectId", null);
        loading.value = ElLoading.service({
          lock: true,
          text: "登录中...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        api
          .postFormAPI("auth/management/login", param, 1)
          .then((res) => {
            if (res.data.code == 1) {
              localStorage.setItem("token", res.data.data);
              api
                .postFormAPI("auth/user/info", {})
                .then((res) => {
                  if (res.data.code == 1) {
                    if (
                      res.data.data.projectList &&
                      res.data.data.projectList.length > 0
                    ) {
                      localStorage.setItem(
                        "projectName",
                        res.data.data.projectList[0].projectName
                      );
                      localStorage.setItem(
                        "logoImg",
                        res.data.data.projectList[0].logoImg
                      );
                      localStorage.setItem(
                        "projectId",
                        res.data.data.projectList[0].id
                      );
                    }
                    localStorage.setItem("ms_username", res.data.data.realName);
                    var info = res.data.data;
                    var userInfo = JSON.stringify(res.data.data);
                    localStorage.setItem("userInfo", userInfo);
                    if (info.passwordExpire == 1) {
                      ElMessage.success("登录成功");
                      loading.value.close();
                      let passwordTime = info.passwordTime || '';
                      let numberdays = DateMinus(passwordTime, pars.getNowTime());
                      // console.log(info.passwordTime)
                      // console.log(pars.getNowTime())
                      if (passwordTime && numberdays > 90) {
                        proxy.$ElMessageBox.confirm("您的密码很久没有修改了，为降低安全风险请修改账户的密码在进行登录", {
                          type: "warning",
                          confirmButtonText: '确定',
                          cancelButtonText: '稍后修改',
                        }).then((res) => {
                          if (res == "confirm") {
                            router.push("/passwd");
                          }
                        }).catch(() => {
                          router.replace("/" + PermissionsPage(info.permissionList));
                        })
                        return
                      } else if (info.passwordTime == null || info.passwordTime == 'null') {
                        proxy.$ElMessageBox.confirm("您正在进行首次账号登录，请修改密码后重新登录平台", {
                          type: "warning",
                          confirmButtonText: '确定',
                          cancelButtonText: '稍后修改',
                        }).then((res) => {
                          if (res == "confirm") {
                            router.push("/passwd");
                          }
                        }).catch(() => {
                          router.replace("/" + PermissionsPage(info.permissionList));
                        })
                        return
                      } else {
                        router.replace("/" + PermissionsPage(info.permissionList));
                      }
                    } else {
                      if (info.permissionList) {
                        operate.operateObj();
                        setTimeout(function () {
                          ElMessage.success("登录成功");
                          router.replace("/" + PermissionsPage(info.permissionList));
                          loading.value.close();
                        }, 1300);
                      } else {
                        router.push("/user");
                      }
                    }
                  } else {
                    if (res.status == 401) {
                      router.push("/login");
                    } else {
                      ElMessage.error(res.data.message);
                    }
                    loading.value.close();
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            } else {
              ElMessage.error(res.data.message);
              loading.value.close();
            }
            //数据处理
          })
          .catch((err) => console.log(err));
      }
    };
    let idx = -1;
    let form = reactive({
      moblie: "",
      smsCode: "",
      affirm_password: "",
      password: "",
    });
    const editVisible = ref(false);
    const handleEdit = (index, row) => {
      idx = index;
      Object.keys(form).forEach((item) => {
        form[item] = row[item];
      });
      editVisible.value = true;
    };
    const store = useStore();
    store.commit("clearTags");
    // 获取验证码
    const showtime = ref(true);
    const count = ref("点击获取验证码");
    const timer = ref(null);
    const sendCode = () => {
      if (!form.moblie) {
        ElMessage.success("请输入手机号");
      } else {
        let TIME_count = 60;
        if (!timer.value) {
          count.value = TIME_count;
          showtime.value = false;
          api
            .postFormAPI(
              "auth/randomCode/mResetPwdPhoneCode",
              {
                phone: form.moblie,
              },
              1
            )
            .then((res) => {
              if (res.data.code == 1) {
                ElMessage.success("验证码已发送");
                timer.value = setInterval(() => {
                  if (count.value > 0 && count.value <= TIME_count) {
                    count.value--;
                  } else {
                    showtime.value = true;
                    clearInterval(timer.value);
                    timer.value = null;
                  }
                }, 1000);
              } else {
                ElMessage.error(res.data.message);
              }
            })
            .catch((err) => console.log(err));
        }
      }
    };

    // 确定找回密码
    const saveEdit = () => {
      if (!form.moblie) {
        ElMessage.error("请输入手机号");
      } else if (!form.smsCode) {
        ElMessage.error("请输入验证码");
      } else if (!form.password) {
        ElMessage.error("请输入新密码");
      } else if (!form.password) {
        ElMessage.error("请确认密码");
      } else if (form.affirm_password != form.password) {
        ElMessage.error("两次密码不一致");
      } else {
        api
          .postFormAPI(
            "auth/management/resetPwdByPhone",
            {
              phone: form.moblie,
              smsCode: form.smsCode,
              password: form.password,
            },
            1
          )
          .then((res) => {
            if (res.data.code == 1) {
              ElMessage.success("登录成功");
              localStorage.setItem("token", res.data.data);
            } else {
              ElMessage.error(res.data.message);
            }
            //数据处理
          })
          .catch((err) => console.log(err));
      }
    };
    return {
      projectType,
      project_Name,
      proxy,
      param,
      rules,
      login,
      form,
      showtime,
      count,
      timer,
      submitForm,
      editVisible,
      handleEdit,
      sendCode,
      isDisabled: false,
      saveEdit,
    };
  },
  mounted() { },
};
</script>

<style lang="less" scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login-bg.jpg);
  background-size: 100%;
}

.login-wrap1 {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login-bg3.jpg);
  background-size: 100%;
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  margin-top: 20px;
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}

.find_password {
  color: #ffffff;
  /* padding-bottom: 20px; */
  cursor: pointer;
}

&:deep(.el-input) {
  // width: auto;
}

.passw {
  font-size: 8px;
}
</style>
